/**
 * Copyright © 2018 陈锦韬  All rights reserved.
 * 
 * @Package: com.rx.init 
 * @author: Administrator   
 * @date: 2018年4月14日 下午2:13:22
 */
package com.rx.init;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import com.rx.core.base.BaseDefaultResp;
import com.rx.core.cfg.SysProperties;
import com.rx.core.dbo.DbTableOperate;
import com.rx.core.enm.RESULT_CODE;
import com.rx.core.enm.RX_ERROR;
import com.rx.core.util.JsonUtils;
import com.rx.service.InitService;
import com.rx.service.inner.ISysCtrlService;

/**
 * @className: SystemInit 
 * @author: Administrator
 * @Description: TODO
 * @date: 2018年4月14日 下午2:13:22
 */
@Service
@EnableConfigurationProperties(SysProperties.class)
public class SystemInit  implements ApplicationListener<ApplicationReadyEvent > {

	public static final Logger logger = LoggerFactory.getLogger(DbTableOperate.class);
	public static boolean first = true;

	@Autowired
	private InitService initService;
	
	@Autowired
	ISysCtrlService sysCtrlService;	
	@Override
	public void onApplicationEvent(ApplicationReadyEvent arg0) {
		try {
			if(first){
				first = false;
				questVer();						
			}

		} catch (Exception e) {
			logger.error(RX_ERROR.SQL_C_ERROR.message()+"：初始化数据库失败");
		}
		
	}
	
	public void questVer() throws Exception{	
		String ouput = sysCtrlService.requestVer(initService.getVerVo());
		if(!initService.isSameTableVer(ouput)){			
			logger.info("数据库版本不一致");
			String ret = sysCtrlService.uploadTableField(initService.getAllTableField());
			BaseDefaultResp respUpload = JsonUtils.toBean(ret, BaseDefaultResp.class);			
			if(!RESULT_CODE.OK.getCode().equals(respUpload.getResultCode())){
				logger.error("数据库字段同步失败");
				return;
			}
		}
		
		// 获取API接口
		String retNetApi = sysCtrlService.getNetApi(initService.getNetApiVo());
		initService.InitNetApi(retNetApi);
		
		// 获取流程
		String retFlow = sysCtrlService.getFlow(initService.getFlowLineVo());
		initService.InitFlow(retFlow);
		
	}

}
